<template>
	<view>
		<view class="topBox">
			<u-image 
				height="278rpx"
				width="100%"
				mode="aspectFill" 
				radius="28rpx"
				src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/065e0e183c344488b6d8ec5207ceaf74.png" 
			/>
		</view>
		<view class="content">
			<view class="flex_wrap row_middle">
				<u-image
					height="58rpx"
					width="256rpx"
					mode="aspectFill" 
					src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/01d775422cdc413a8f048661bb2750c0.png" 
				/>
				<view class="agreement" @click="toUserAgreement('MEMBERSHIP_AGREEMENTMEMBERSHIP_AGREEMENT')">《会员权益规则》</view>
			</view>
			<view class="content_box">
				<u-grid :border="false" col="3">
					<u-grid-item v-for="(listItem,listIndex) in list" :key="listIndex" @click="toPage(listItem.type,listItem.path)">
						<u-icon :customStyle="{paddingTop:40+'rpx'}" :name="listItem.name" size="80rpx"
							labelColor="#663B00" labelSize="22rpx"></u-icon>
						<text :class="listItem.type == '1' ? 'grid-text2' : 'grid-text'">{{listItem.title}}</text>
						<text class="grid-text1">{{listItem.title1}}</text>
					</u-grid-item>
				</u-grid>
			</view>
			<view class="flex_wrap row_middle">
				<u-image
					height="48rpx"
					width="268rpx"
					mode="aspectFill" 
					src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/31a99616df9d43988c69a75dc2983844.png" 
				/>
				<view v-if="btnShow == 'false'">
					<u-button :customStyle="receiveBtn" text="填写地址" color="linear-gradient( 180deg, #FFDC79 0%, #D95F1F 100%)" shape="circle" @click="receiveAddress" />
				</view>
			</view>
			<view class="imgBox">
				<view v-for="(item,index) in imgList" :key="index" style="margin-bottom: 18rpx;" @click="clickImg(item.type,item.path)">
					<u-image
						height="156rpx"
						width="326rpx"
						mode="aspectFill" 
						:src="item.imgPath" 
					/>
				</view>
			</view>
		</view>
		<view class="bgcards" v-if="btnShow == true">
			<!-- <u-button :customStyle="buttonCustomStyle" @click="dzShow" /> -->
			<view>
				<u-button color="#32303D" shape="circle" :customStyle="buttonQWstyle1" text="他人代付" @click="dzShow1" /> 
				<!-- openType="share" -->
			</view>
			<view>
				<u-button color="linear-gradient( 222deg, #FCBB7A 0%, #FADFB3 100%);" shape="circle" :customStyle="buttonSharetyle1" @click="dzShow" text="立即开通,支付￥365" />
			</view>
		</view>
		<!-- <view class="bgcards" v-if="btnShow == 'false'">
			<u-button :customStyle="buttonCustomStyle1" openType="share" />
		</view> -->
		
		<u-modal :show="nameShow" ref="editModal" title="申请会员姓名" showCancelButton @confirm="confirmEdit"
			@cancel="cancelEdit" confirmColor="#1682FF">
			<view slot="default" style="width: 100%">
				<u--input type="text" placeholder="请输入申请会员姓名" clearable v-model="userNmae" :customStyle="{
		            background: '#F7F7F7',
		            borderRadius: '16rpx 16rpx 16rpx 16rpx',
		            border: 'none',
		            height: '80rpx',
		            marginTop: '20rpx',
		        }" :placeholderStyle="{
		            fontSize: '28rpx',
		            color: '#F7F7F7',
		        }"></u--input>
			</view>
		</u-modal>
		
		<view class="bgcards" v-if="btnShow == 'false'">
			<view>
				<u-button color="#32303D" shape="circle" :customStyle="buttonQWstyle" text="分享二维码" @click="qwBtn" />
			</view>
			<view>
				<u-button color="linear-gradient( 222deg, #FCBB7A 0%, #FADFB3 100%);" shape="circle" :customStyle="buttonSharetyle" openType="share" text="立即分享" />
			</view>
		</view>
		
		
		
		<u-popup
		    :show="showQR"
		    mode="center"
		    @close="showQR = false"
		    @touchmove.stop.prevent="() => {}"
		>
		    <view>
		        <u--image
		            :src="showImgData"
		            width="200px"
		            height="200px"
		        ></u--image>
		        <u-text
		            text="长按转发或下载"
		            size="32rpx"
		            color="#3D3D3D"
		            align="center"
		            margin="20rpx 0"
		        />
		    </view>
		</u-popup>
		
		
		<u-popup :round="20" :show="showAddress" :closeOnClickOverlay="false" @close="close" @open="open">
			<view>
				<view class="takeAddress">
					<text>收货地址</text>
					<view @click="closeAddress" class="closeAddress">
						<u-icon name="close" color="#7B7B7B" size="20" bold />
					</view>
				</view>
				<view class="box">
					<view class="manageAddress flex_wrap row_between row_middle">
						<view>常用地址</view>
						<u-icon @click="addAddress" name="plus" size="30rpx" color="#538CFF " label="新增"
							labelSize="32rpx" labelColor="#538CFF" space="4rpx" />
					</view>
					<view class="noaddress" v-if="addressList.length == 0">
						<u-icon
							name="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/11/27/e12ad7ba162b47b1a8e59083e226583a.png"
							size="160rpx" labelSize="28rpx" labelColor="#999" space="48rpx" label="暂无任何收货地址"
							labelPos="bottom" />
					</view>
					<view class="address_list" v-if="addressList.length > 0">
						<scroll-view scroll-y="true" class="address_list_elsebg'">
							<view v-for="(address, index) in addressList" :key="address"
								class="address_list_elsebgList">
								<view class="flex_wrap row_between">
									<u-icon
										name="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/11/27/4fa0ed23eaf647fea0671129e6483dcf.png"
										size="61rpx"></u-icon>
									<view class="locations">
										<view class="locations_name flex_wrap">
											<text>{{ address.consigneeName }}</text>
											<text>{{
				                                address.consigneeMobile
				                            }}</text>
											<text class="default" v-if="address.defaultAddress == '1'">默认</text>
										</view>
										<view class="locations_detail">{{ address.province }}{{ address.city
				                            }}{{ address.county
				                            }}{{ address.address }}</view>
									</view>
									<u-radio-group placement="column" @change="groupChange" v-model="radiovalue1">
										<u-radio :name="address.id" :key="index" iconSize="50rpx" size="60rpx"
											inactiveColor="#999" activeColor="#588BF3 " />
									</u-radio-group>
								</view>
								<u-gap marginTop="32rpx" marginBottom="20rpx" height="2rpx;" bgColor="#F3F3F3" />
								<view class="flex_wrap row_between del">
									<u-icon name="trash-fill" label="删除" labelSize="24rpx" @click="
				                            del(address.id, address.defaultAddress)
				                        " />
									<u-icon
										name="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/11/27/3ce1b395adcf42e2996774f6d8bdca3b.pn"
										bold label="编辑" labelSize="24rpx" labelColor="#588BF3"
										@click="to_edit(address.id)" />
								</view>
							</view>
						</scroll-view>
					</view>
					<u-button v-if="shareFriendBtn == '1'" text="确定选中111" color="#588BF3" :customStyle="{
				            ...buttonCustomStyle2,
				            width: '694rpx',
				            marginBottom: '80rpx',
				        }" shape="circle" @click="sureAddress" />
					<u-button v-if="shareFriendBtn == '2' && !this.radiovalue1" text="选中后分享" color="#588BF3" :customStyle="{
					        ...buttonCustomStyle2,
					        width: '694rpx',
					        marginBottom: '80rpx',
					    }" shape="circle" @click="sureAddress" />
					<u-button v-if="shareFriendBtn == '2' && this.radiovalue1" text="选中后分享1" color="#588BF3" :customStyle="{
					        ...buttonCustomStyle2,
					        width: '694rpx',
					        marginBottom: '80rpx',
					    }" shape="circle" @click="sureAddress" />
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import caches from "@/config/caches.js";
	import { encryption } from "@/utils/encryption.js";
	import { chickUrl } from "@/config/tendIdConfig.js";
	import {
		toBeSalesman,
		placeChickenAnOrder,
		checkHaveOrderMember,
		getReceiveBtn
	} from "@/api/card.js";
	import { getMiniCodeByAppId } from "@/api/order.js";
	import {
		getShippingAddress,
		deleteAddress,
		editDefaultAddress,
		editAddressIdForOrder
	} from "@/api/shop.js";
	import store from "@/store";
	import {
		mapGetters
	} from "vuex"
	import {
		getCustomerInfoByToken,
		updateCustomerByCustomerId
	} from "@/api/login.js";
	export default {
		data() {
			return {
				nameShow: false,
				userNmae:'',
				showQR: false,
				appId: this.$appId,
				showImgData: "",
				buttonSharetyle:{
					width: '330rpx',
					height: '96rpx',
					color: '#35333F',
					fontSize:'40rpx',
				},
				buttonSharetyle1:{
					width: '436rpx',
					height: '96rpx',
					color: '#35333F',
					fontSize:'40rpx',
				},
				buttonQWstyle:{
					width: '330rpx',
					height: '96rpx',
					color: '#FFFFFF',
					fontSize:'40rpx'
				},
				buttonQWstyle1:{
					width: '226rpx',
					height: '96rpx',
					color: '#FFFFFF',
					fontSize:'40rpx'
				},
				buttonCustomStyle: {
					height: "98rpx",
					background: "url(https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/11/19/87a0cf4bb8ea4895a09c812c7e1ec058.png) no-repeat",
					backgroundSize: "cover",
					backgroundPosition: "center",
					border: "none",
					borderRadius: '88rpx',
				},
				buttonCustomStyle1: {
					height: "98rpx",
					background: "url(https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/11/19/a035b628a97546128a64b196a930e886.png) no-repeat",
					backgroundSize: "cover",
					backgroundPosition: "center",
					border: "none",
					borderRadius: '88rpx',
				},
				salesmanId: "",
				authority: this.$store.getters?.authority,
				btnShow: true,
				receiveBtn: {
					width: '156rpx',
					height: '48rpx',
					color: '#fff',
					marginLeft:'30rpx'
				},
				
				imgList:[
					{
						imgPath:'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/0e48e5cd83c74ceb8442de3f44d5261e.png',
						path:'pages_shop1/goods/index?id=1788027534840037378',
						type:'1'
					},
					{
						imgPath:'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/0674640b8bd6439fb5667817427e2fc4.png',
						path:'pages_shop1/goods/index?id=1821438655969705986',
						type:'2'
					},
					{
						imgPath:'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/c2be3063efcc4b23ba4ad8090834971e.png',
						path:'pages_shop1/goods/index?id=1821437881410465794',
						type:'3'
					},
					{
						imgPath:'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/763c9d10046447ca81dfb8ce5e1bdaf8.png',
						type:'4'
					}
				],
				list: [
					{
						name: 'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2025/01/14/c7b8207dada3457fa8825bb37eb2956c.png',
						title: '私人健康管家 ',
						title1: '精准健康管理及专业解读',
						type: '1',
					},
					{
						name: 'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/36e456489e0a40d3b595bf631cf37c1f.png',
						title: '2万元大panel',
						title1: '精准用药检测',
						type: '2',
					},
					{
						name: 'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/916748676c2046a9ba645490290f423d.png',
						title: '前沿医疗',
						title1: '对接前沿医疗科学机构',
						type: '3',
					},
					{
						name: 'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/bf34204296204cf4bb640ffba7fc3285.png',
						title: '健康数字人',
						title1: 'AI数字人健康护航',
						type: '4',
						path: "/pages_else/order/index",
					},
					{
						name: 'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/0e2099205a4643eb9bdb410f9271eb5f.png',
						title: '服务首享',
						title1: '新项目首享资格',
						type: '5',
					},
					{
						name: 'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/12/02/7b25717e10dd46ff866b6f284b113f1f.png',
						title: '健康讲座',
						title1: '精准医疗课程分享',
						type: '6',
					},
				],
				
				showAddress: false,
				ShippingAddress: {},
				radiovalue1: "", //默认选中
				changeDetail: "", //切换选中的
				buttonCustomStyle2: {
					width: "526rpx",
					height: "80rpx",
					outline: "none",
					border: "none",
				},
				consigneeId: "",
				orderNum: '',
				
				shareFriendBtn:'1'
			}
		},
		onLoad(op) {
			console.log(op, "有推荐人");
			this.salesmanId = op.salesmanId || op.scene;
			this.btnShow = op.btnShow;
			// 解决微信扫码登录 新用户登录跳回 该页面
			var pages = getCurrentPages(); // 获取栈实例
			console.log(pages, 'pages>>>')
			if (pages.length === 1) {
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				let currentPage = pages[pages.length - 1]["$page"]["fullPath"]; //当前页面路径(带参数)
				uni.setStorageSync("loginBackUrl", currentPage);
			}
			if (!this.isLogin) return uni.reLaunch({
				url: "/pages/user/phone/indexApp"
			})
		},
		computed: mapGetters(["isLogin", "userInfo", "addressList"]),
		created() {
			this.isLogin && this.$store.dispatch("GET_ADDRESS_LIST");
		},
		methods: {
			clickImg(type,path){
				if(type == 4){
					this.toChicken()
				}else{
					uni.$u.route({
					    url: path,
					});
				}
				
			},
			toChicken() {
			    const phone = uni.getStorageSync(caches.PHONE);
			    // 使用 uni.request 替换 wx.request，支持跨平台
			    uni.request({
			        url: chickUrl + "/api/v1/auth/phone-login",
			        method: "POST",
			        data: {
			            ...encryption({
			                user_phone: phone,
			            }),
			        },
			        success: (res) => {
			            this.token = res.data.data.token;
			            // 使用 uni.navigateTo 替换 wx.navigateTo，支持跨平台
			            uni.navigateTo({
			                url: `/pages_shop1/pay/chickenDetail/jump?url=${encodeURIComponent(
			                    chickUrl + "/go"
			                )}&api_token=${this.token}`,
			            });
			            console.log(this.token, "11");
			        },
			        fail: (err) => {
			            console.log(err, "22");
			        },
			    });
			},
			async qwBtn(){
				await getCustomerInfoByToken().then((res) => {
					this.customerId = res.data.id;
				});
				const that = this;
				const params = {
				    page: "pages_my1/beSalesman/index",
				    scene: that.customerId ,
				    env_version: __wxConfig.envVersion,
				    check_path: false,
				    appId: that.appId,
				};
				getMiniCodeByAppId(params).then((res) => {
				    if (res.code === 200 && res.data) {
				        that.showQR = true;
				        var showImgData = res.data;
				        that.showImgData = "data:image/png;base64," + showImgData;
				    }
				});
			},
			
			
			
			toUserAgreement(code) {
				uni.navigateTo({
					url: "/pages/agreement/userAgreement/index?code=" + code
				})
			},
			changeAddress(id) {
				this.consigneeId = id;
			},
			
			receiveAddress(){
				uni.navigateTo({
					url: "/pages_my1/beSalesman/detail"
				})
			},
			onShareTimeline: function() {
				return {
					title: this.$appletName,
					path: "pages_my1/beSalesman/index",
				};
			},
			async onShareAppMessage(res) {
				await getCustomerInfoByToken().then((res) => {
					this.customerId = res.data.id;
				});
				const path =
					this.authority === "salesman" ?
					"/pages_my1/beSalesman/index?salesmanId=" + this.customerId :
					"/pages_my1/beSalesman/index?salesmanId=" + this.userInfo.id;
				return {
					title: this.$appletName,
					path
				};
			},
			cancelEdit() {
				this.userNmae = "";
				this.nameShow = false;
			},
			async confirmEdit() {
				if (!this.userNmae)
					return uni.showToast({
						title: "请输入申请会员姓名",
						icon: "none",
					});
				const paramsUserInfo = {
					nickName: this.userNmae,
					id: this.userInfo.id,
				};
				updateCustomerByCustomerId(paramsUserInfo).then(
					(res) => {
						console.log(res, '>>>>')
						this.cancelEdit();
						this.toLoginSuccess()
					}
				);
			},
			dzShow(){
				this.shareFriendBtn = '1'
				this.showAddress = true;
			},
			dzShow1(){
				this.shareFriendBtn = '2'
				this.showAddress = true;
			},
			
			
			async toLoginSuccess() {
				const res = await checkHaveOrderMember();
				if (res.data) {
					uni.$u.toast("您已是会员，无需再次支付！");
					return;
				}
				const userRes = await getCustomerInfoByToken();
				if (!userRes.data.nickName) {
					this.nameShow = true
					return;
				}
				let data;
				let params = {
					affCustomerId: this.salesmanId, //推荐人客户ID
					appId: this.$appId,
					consigneeId:this.radiovalue1
				};
				const result = await placeChickenAnOrder(params);
				console.log(result,'222222')
				data = result.data;
				const that = this;
				uni.requestPayment({
					provider: "wxpay",
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.packageValue,
					signType: "MD5",
					paySign: data.paySign,
					success: function(res) {
						if (res.errMsg === "requestPayment:ok") {
							uni.$u.toast('已成为会员！');
							// that.getReceive()
							uni.reLaunch({
								url: "/pages/my/index"
							})
						}
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					},
				});
			},
			
			
			open() {},
			close() {
				this.showAddress = false;
			},
			//修改选中地址按钮
			groupChange(n) {
				this.changeDetail = this.addressList.filter((v) => v.id === n)[0];
			},
			sureAddress() {
				console.log(this.addressList, 'this.addressList>>>')
				if (!this.addressList.length) return this.addAddress();
				if (!this.radiovalue1) return uni.$u.toast("请先勾选地址！");
				this.showAddress = false;
				this.toLoginSuccess()
			},
			async getReceive() {
				const res = await getReceiveBtn();
				this.orderNum = res.data.orderNum
				console.log(this.orderNum)
				this.editOrderAddress()//关联地址
			},
			editOrderAddress() {
				const params = {
					consigneeId: this.radiovalue1,
					orderNum: this.orderNum,
				};
				console.log(params, "params地址切换");
				editAddressIdForOrder(params).then((res) => {
					uni.reLaunch({
						url: "/pages/my/index"
					})
				});
			},
			
			//删除地址
			del(id, defaultAddress) {
				console.log(id, defaultAddress, "删除");
				const that = this;
				uni.showModal({
					title: "",
					content: "确定要删除该地址吗？",
					success({
						confirm,
						cancel
					}) {
						if (confirm) {
							deleteAddress(id).then((res) => {
								uni.$u.toast("删除成功！");
								that.getShippingAddress();
							});
						}
					},
				});
			},
			closeAddress() {
				this.showAddress = false;
			},
			// 获取地址列表
			getShippingAddress(pageNo, pageSize) {
				this.$store.dispatch("GET_ADDRESS_LIST");
			},
			// 编辑按钮
			to_edit(key) {
				uni.navigateTo({
					url: "/pages_shop1/userAddress/edit?addressId=" + key,
				});
			},
			// 新增按钮
			addAddress() {
				uni.navigateTo({
					url: "/pages_shop1/userAddress/index",
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.topBox{
		background-color: #FBF4E8;
		padding: 40rpx 40rpx 0 40rpx;
		position: relative;
	}
	.content{
		background: #F3F3F3;
		border-radius: 48rpx 48rpx 0 0;
		margin-top: -66rpx;
		position: absolute;
		width: 100%;
		padding: 22rpx 40rpx 0 40rpx;
		&_box{
			margin : 20rpx 0 26rpx;
			padding:0 0 40rpx 0;
			background: #FFFFFF;
			border-radius: 20rpx;
		}
	}
	.grid-text {
		font-size: 28rpx;
		color: #333333;
		padding: 16rpx 0 10rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}
	.grid-text2 {
		font-size: 28rpx;
		color: linear-gradient(90deg, #FFDC79 0%, #D95F1F 100%);
		padding: 16rpx 0 10rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}
	.grid-text1 {
		font-size: 20rpx;
		color: #777;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}
	.imgBox{
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin-top: 24rpx;
	}
	.bgcards {
		width: 100%;
		padding: 18rpx 30rpx;
		background-color: #fff;
		height: 176rpx;
		position: fixed;
		bottom: 0;
		display: flex;
		justify-content: space-between;
	}
	.agreement{
		color: $uni-color-primary !important;
		margin-left: 20rpx;
	}
	
	
	// 收货地址弹框
	.takeAddress {
		height: 120rpx;
		background: #e2ebff;
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		line-height: 120rpx;
		text-align: center;
		font-size: 40rpx;
		font-weight: 500;
		color: #3d3d3d;
	}
	.manageAddress {
		padding: 28rpx 28rpx 28rpx 40rpx;
		font-size: 32rpx;
		font-weight: 500;
		color: #333333;
	}
	.noaddress {
		margin: 120rpx auto 240rpx;
	}
	.address_list {
		padding: 0 28rpx 92rpx;
		// max-height: 900rpx;
		overflow: hidden;
		&_bg {
			padding: 40rpx 28rpx 32rpx;
			max-height: 900rpx;
			background: #ffffff;
			border-radius: 20rpx;
			overflow-y: auto;
		}
	
		&_elsebg {
			max-height: 900rpx;
			border-radius: 20rpx;
			// overflow-y: auto;
		}
	
		&_elsebgList {
			background: #ffffff;
			border-radius: 20rpx;
			margin-bottom: 40rpx;
			padding: 40rpx 28rpx 12rpx;
		}
	}
	.del {
		padding-left: 88rpx;
	}
	.locations {
		width: 100%;
		padding: 0 16rpx 0 26rpx;
		text-align: left;
	
		&_name {
			font-size: 28rpx;
			color: #3d3d3d;
			font-weight: 500;
	
			text {
				margin-right: 32rpx;
			}
	
			.default {
				margin-left: -12rpx;
				width: 86rpx;
				height: 36rpx;
				border-radius: 4rpx;
				border: 2rpx solid #588bf3;
				font-size: 24rpx;
				color: #588bf3;
				display: block;
				text-align: center;
				font-weight: 400;
			}
		}
	
		&_detail {
			size: 24rpx;
			color: #666;
			font-weight: 400;
		}
	}
	.closeAddress {
		position: absolute;
		top: 40rpx;
		right: 32rpx;
	}
</style>